<template>
  <div class="login-main" v-loading="changeRegLoading || submitLoading">
    <form class="form" @submit.prevent="submit">
      <div class="flex-column">
        <label>账户</label>
      </div>
      <div class="inputForm">
        <img src="~@/assets/login/email.svg" alt="email" />
        <input type="text" class="input" v-model="loginObj.userId" placeholder="您的账户" />
      </div>

      <div class="flex-column">
        <label>密码</label>
      </div>
      <div class="inputForm">
        <img src="~@/assets/login/pass.svg" alt="password" />
        <input
          :type="showPassword ? 'text' : 'password'"
          class="input"
          v-model="loginObj.password"
          placeholder="您的密码"
        />
        <img
          src="~@/assets/login/eye.svg"
          alt="toggle password visibility"
          class="eye-icon"
          @click="togglePasswordVisibility"
        />
      </div>

      <div v-if="regState" class="flex-column">
        <label>确认密码</label>
      </div>
      <div v-if="regState" class="inputForm">
        <img src="~@/assets/login/pass.svg" alt="password" />
        <input
          :type="showConfirmPassword ? 'text' : 'password'"
          class="input"
          v-model="loginObj.affirmPassword"
          placeholder="确认密码"
        />
        <img
          src="~@/assets/login/eye.svg"
          alt="toggle confirm password visibility"
          class="eye-icon"
          @click="toggleConfirmPasswordVisibility"
        />
      </div>

      <!-- 记住我选项 - 仅在登录时显示 -->
      <div v-if="!regState" class="remember-me-container">
        <el-checkbox v-model="loginObj.rememberMe">记住我</el-checkbox>
      </div>

      <button type="submit" class="button-submit">{{ regState ? '注 册' : '登 录' }}</button>

      <p class="p" v-if="!regState">
        没有账户?
        <span class="span" @click="toggleRegisterState">注 册</span>
      </p>
      <p class="p" v-else>
        点击返回
        <span class="span" @click="toggleRegisterState">登 录</span>
      </p>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      regState: false,
      showPassword: false,
      showConfirmPassword: false,
      changeRegLoading: false,
      submitLoading: false,
      loginObj: {
        userId: '', // 修改为userId以匹配接口文档
        password: '',
        affirmPassword: '',
        rememberMe: false // 添加记住我选项
      }
    }
  },
  created() {
    this.$emit('updateBar')
    // 检查自动登录
    this.checkAutoLogin()
  },
  methods: {
    // 检查自动登录
    async checkAutoLogin() {
      try {
        const autoLoginResult = await window.api.checkAutoLogin();
        if (autoLoginResult && autoLoginResult.success) {
          this.$message({
            message: '自动登录成功！',
            type: 'success'
          });

          // 直接跳转到主界面
          const screenWidth = window.screen.width;
          const screenHeight = window.screen.height;
          const calculatedWidth = Math.floor((screenWidth / 5) * 3) + 250;
          const calculatedHeight = 800;

          window.ipcRenderer.send('toMain', {
            username: autoLoginResult.user?.username || 'auto',
            token: autoLoginResult.token || '',
            screenWidth: calculatedWidth,
            screenHeight: calculatedHeight
          });

          this.$router.push('/main');
        }
      } catch (error) {
        console.log('无自动登录或自动登录失败:', error);
      }
    },

    // 切换注册状态
    toggleRegisterState() {
      this.changeRegLoading = true
      setTimeout(() => {
        this.regState = !this.regState
        if (!this.regState) {
          this.loginObj.userId = ''
          this.loginObj.password = ''
          this.loginObj.affirmPassword = ''
        }
        this.changeRegLoading = false
      }, 1000)
    },

    // 显隐密码
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword
    },
    toggleConfirmPasswordVisibility() {
      this.showConfirmPassword = !this.showConfirmPassword
    },

    // 提交表单
    submit() {
      // 校验逻辑
      if (!this.loginObj.userId || !this.loginObj.password) {
        this.$message({
          message: '请输入完整的账户信息！',
          type: 'info'
        })
        return
      }
      if (this.regState && this.loginObj.password !== this.loginObj.affirmPassword) {
        this.$message({
          message: '两次输入的密码不一致！',
          type: 'error'
        })
        return
      }
      this.submitLoading = true

      console.log('提交数据:', this.loginObj)
      console.log('loginObj JSON:', JSON.stringify(this.loginObj))

      if (this.regState) {
        // 注册逻辑
        window.api.register({
          userId: this.loginObj.userId,
          password: this.loginObj.password
        })
          .then((response) => {
            if (response && response.success) {
              this.$message({
                message: '注册成功！',
                type: 'success'
              })
              // 注册成功后，切换到登录模式并清空密码
              this.regState = false
              this.loginObj.password = ''
              this.loginObj.affirmPassword = ''
            } else {
              this.$message({
                message: response.message || '注册失败',
                type: 'error'
              })
            }
          })
          .catch(err => {
            this.$message({
              message: err.message || '注册失败',
              type: 'error'
            })
          })
          .finally(() => {
            this.submitLoading = false
          })
      } else {
        // 登录逻辑
        const loginData = {
          userId: this.loginObj.userId,
          password: this.loginObj.password,
          rememberMe: this.loginObj.rememberMe
        }

        window.api.login(loginData)
          .then((response) => {
            if (response && response.success) {
              this.$message({
                message: '登录成功！',
                type: 'success'
              })

              const screenWidth = window.screen.width
              const screenHeight = window.screen.height
              const calculatedWidth = Math.floor((screenWidth / 5) * 3) + 250
              const calculatedHeight = 800

              window.ipcRenderer.send('toMain', {
                username: this.loginObj.userId,
                token: response.token || '',
                screenWidth: calculatedWidth,
                screenHeight: calculatedHeight
              })

              this.$router.push('/main')
            } else {
              this.$message({
                message: response.message || '登录失败',
                type: 'error'
              })
            }
          })
          .catch(err => {
            this.$message({
              message: err.message || '登录请求失败',
              type: 'error'
            })
          })
          .finally(() => {
            this.submitLoading = false
          })
      }
    },

    // 显示升级提示
    showServiceUpgradeMessage(type) {
      if ('face' === type) {
        this.$router.push('/face')
      } else {
        window.open('https://www.baidu.com/', '_blank')
      }
    }
  }
}
</script>

<style>
@import './index.css';

.remember-me-container {
  margin: 10px 0;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.el-loading-spinner .path {
  stroke: #151717 !important;
}

.el-loading-mask {
  border-radius: 20px !important;
  width: 510px !important;
}
</style>
